package p_400

import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress

/**
 * UDP 的服务
 */
class UDPPoke(val address: InetAddress, val port: Int,
              var bufferSize: Int = 8192, var timeout: Int = 30000) {


    fun poke(): ByteArray? {
        try {
            val socket = DatagramSocket(0)
            val outGoing = DatagramPacket(ByteArray(1), 1, address, port)
            socket.connect(address, port)
//            socket.soTimeout(timeout)
            socket.send(outGoing)
            val incoming = DatagramPacket(ByteArray(bufferSize), bufferSize)
            socket.receive(incoming)
            val numberBytes = incoming.length
            val response = ByteArray(numberBytes)
            System.arraycopy(incoming.data, 0, response, 0, numberBytes)
            return response
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

}
